from gui.gui_base import GuiBase
from model.exception import ParkTokenFatalError, ParkTokenFindImageError
import sys
import os
import pyautogui

pyautogui.PAUSE = 0.3  # 每次调用后等待


class WindowGui(GuiBase):
    def __init__(self):
        super().__init__()
        self.hwnd = None
        self.search_time = 60
        self.confidence = 0.8
        self.grayscale = True

    def check_env(self):
        if not self.hwnd:
            raise ParkTokenFatalError("未设置窗口句柄")

    # 资源文件目录访问
    def source_path(self, relative_path):
        # 是否Bundle Resource
        if getattr(sys, "frozen", False):
            base_path = sys._MEIPASS
        else:
            base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)

    def click_image(self, image_path: str):
        """点击图片"""

        point = self.find_point_by_image(self.source_path(image_path))
        pyautogui.click(point)

    def hotkey(self, *args):
        """按键"""

        pyautogui.hotkey(*args)

    def set_hwnd(self, hwnd):
        self.hwnd = hwnd

    def find_point_by_image(self, image_path: str):
        """根据图片找到对应的坐标"""

        point = pyautogui.locateCenterOnScreen(
            image_path,
            confidence=self.confidence,
            grayscale=self.grayscale,
            minSearchTime=self.search_time,
        )

        if not point:
            raise ParkTokenFindImageError(image_path)

        return point

    def start(self):
        pass
